package com.example.yskjproject.view.dialog;


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;

import com.example.yskjproject.R;
import com.example.yskjproject.content.EventContent;
import com.example.yskjproject.event.EventMessage;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.http.callback.JsonCallback;
import com.example.yskjproject.model.FollowModel;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.utils.EventBusUtil;
import com.example.yskjproject.utils.SpCashUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.qcloud.tuicore.util.ToastUtil;

import java.util.HashMap;
import java.util.Map;

import es.dmoral.toasty.Toasty;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * WorkDialogHelper  删除订单
 * <p>
 * 作者：zx
 * 创建时间：2024/4/24
 */
public class OrderDialog extends Dialog {

    public static int REQUEST_SELECT_IMAGES_CODE = 0x01;

    private Context context;

    private static AppCompatImageView imgColose;


    private Gson gson = new Gson();

    private AppCompatButton btQx, btOk;
    private String orderId;
    private int userId;

    private String type = "";


    public OrderDialog(@NonNull Context context, String orderId, int userId, String type) {
        super(context);
        this.context = context;
        this .orderId  = orderId;
        this.userId = userId;
        this.type = type;
        setContentView(R.layout.delect_dialog);
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imgColose = findViewById(R.id.img_colose);
        imgColose.setOnClickListener(exit -> dismiss());
        AppCompatTextView orderContent =   findViewById(R.id.order_content);

        switch (type){
            case "delete":
                orderContent.setText("是否确认删除订单？");
                break;
            case "refund":
            case "jltk":
                orderContent.setText("是否确认当前订单退款？");
                break;


        }

        Window window = getWindow();
        if (window != null) {
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.gravity = Gravity.CENTER;
            layoutParams.width = (int) (getContext().getResources().getDisplayMetrics().widthPixels); // 设置宽度
            layoutParams.height = (int) (getContext().getResources().getDisplayMetrics().heightPixels * 0.3); // 设置高度
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            window.setAttributes(layoutParams);
        }
        setCanceledOnTouchOutside(false);
        setDateInfo();
    }

    /**
     * 设置我的工作室内容
     */
    @SuppressLint("NotifyDataSetChanged")
    private void setDateInfo() {
        findViewById(R.id.img_colose).setOnClickListener(dis -> dismiss());
        //name
        btQx = findViewById(R.id.bt_qx);
        btQx.setOnClickListener(cancle -> dismiss());
        //简介
        btOk = findViewById(R.id.bt_ok);
        btOk.setOnClickListener(btOk -> {
            if( SpCashUtils.getInstance().getUserId() == userId){
                switch (type){
                    case "delete":
                        delectOrderId(orderId);
                        break;
                    case "refund":
                        refundOrderId(orderId);
                        break;
                    case "jltk":
                        okOrder(orderId);
                        break;

                }

            }else{
                ToastUtil.toastLongMessage("不能操作不是自己得订单！");
            }
        });
    }

    /**
     * todo 删除订单
     * @param orderId
     */
    private void delectOrderId(String orderId){
        OkGo.<LzyResponse>get(Urls.DELETE_ORDER + "?order_id=" + orderId).execute(new JsonCallback<LzyResponse>() {
            @Override
            public void onSuccess(Response<LzyResponse> response) {
                if (response.body() == null){
                    ToastUtil.toastShortMessage("服务器返回为空！");
                    return;
                }
                if (TextUtils.equals("ok", response.body().msg)) {
                    ToastUtil.toastShortMessage("删除订单成功");
                    EventBusUtil.sendEvent(new EventMessage(EventContent.update_order_data));
                    dismiss();
                }else {
                    ToastUtil.toastShortMessage(response.body().msg);
                }
            }

            @Override
            public void onError(Response<LzyResponse> response) {
                super.onError(response);
            }
        });
    }



    /**
     * todo 退款
     * @param orderId
     */
    private void refundOrderId(String orderId){
        Map<String, Object> jsonParams = new HashMap<>();
        jsonParams.put("order_sn", orderId);
        String paramsDate = gson.toJson(jsonParams);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
        OkGo.<LzyResponse>post(Urls.NO_ORDER).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse>() {
            @SuppressLint("SimpleDateFormat")
            @Override
            public void onSuccess(Response<LzyResponse> response) {
                if (response.body() == null){
                    ToastUtil.toastShortMessage("服务器返回为空！");
                    return;
                }
                if (TextUtils.equals("ok", response.body().msg)) {
                    ToastUtil.toastShortMessage("订单退款成功");
                    EventBusUtil.sendEvent(new EventMessage(EventContent.update_order_data));
                    dismiss();
                }else {
                    ToastUtil.toastShortMessage(response.body().msg);
                }
            }

            @Override
            public void onError(Response<LzyResponse> response) {
                super.onError(response);
                ToastUtil.toastShortMessage("退款失败");
            }
        });


        OkGo.<LzyResponse>get(Urls.NO_ORDER + "?order_id=" + orderId).execute(new JsonCallback<LzyResponse>() {
            @Override
            public void onSuccess(Response<LzyResponse> response) {
                if (response.body() == null){
                    ToastUtil.toastShortMessage("服务器返回为空！");
                    return;
                }
                if (TextUtils.equals("ok", response.body().msg)) {
                    ToastUtil.toastShortMessage("删除订单成功");
                    EventBusUtil.sendEvent(new EventMessage(EventContent.update_order_data));
                    dismiss();
                }else {
                    ToastUtil.toastShortMessage(response.body().msg);
                }
            }

            @Override
            public void onError(Response<LzyResponse> response) {
                super.onError(response);
            }
        });
    }


    private void okOrder(String orderSn) {
        Map<String, Object> jsonParams = new HashMap<>();
        jsonParams.put("order_sn", orderSn);
        jsonParams.put("state", 2);
        String paramsDate = gson.toJson(jsonParams);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
        OkGo.<LzyResponse>post(Urls.OK_ORDER).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse>() {
            @SuppressLint("CheckResult")
            @Override
            public void onSuccess(Response<LzyResponse> response) {
                if (response.body() == null){
                    ToastUtil.toastShortMessage("服务器返回为空！");
                    return;
                }
                if (response.body().code == 0) {
                    ToastUtil.toastShortMessage(response.body().msg);
                } else{
                    ToastUtil.toastShortMessage(response.body().msg);
                }
            }

            @Override
            public void onError(Response<LzyResponse> response) {
                super.onError(response);
            }
        });
    }

    @Override
    public void dismiss() {
        super.dismiss();
    }

}
